package com.susallwave.srcb.config;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.util.Date;

/**
 * @author ljhh
 */
@EnableTransactionManagement
@Configuration
public class MybatisPlusPageConfig implements MetaObjectHandler {

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }

    @Override
    public void insertFill(MetaObject metaObject) {
        String currentUserId = getCurrentUserId();

        // 创建信息
        this.strictInsertFill(metaObject, "creator", String.class, currentUserId);
        this.strictInsertFill(metaObject, "createTime", Date.class, new Date());

        // 更新信息（创建时与创建信息相同）
        this.strictInsertFill(metaObject, "updater", String.class, currentUserId);
        this.strictInsertFill(metaObject, "updateTime", Date.class, new Date());

        // 逻辑删除标记
        this.strictInsertFill(metaObject, "del", Integer.class, 0);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        String currentUserId = getCurrentUserId();

        // 更新信息
        this.strictUpdateFill(metaObject, "updater", String.class, currentUserId);
        this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date());
    }

    /**
     * 智能获取当前操作者ID
     */
    private String getCurrentUserId() {

        try {
            if (StpUtil.isLogin()) {
                return StpUtil.getLoginIdAsString();
            }
        } catch (Exception e) {
            // 记录日志或忽略
        }
        return "system";
    }
}